package yml;

import org.springframework.beans.factory.config.YamlProcessor;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

/**
 * .
 *
 * @author sunhao(sunhao.java @ gmail.com)
 * @version 1.0 2018/1/9 下午10:55
 */
public class SpringYamlTest {

    public static void main(String[] args) {
        SpringYamlTest test = new SpringYamlTest();
        Resource resource = new ClassPathResource("yml/application.yml");

        Map<String, Object> propertySource = test.load(resource);
        System.out.println(propertySource);

        Properties properties = test.loadBySpring(resource);
        System.out.println(properties);
    }

    private Properties loadBySpring(Resource resource) {
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();

        factoryBean.setSingleton(true);
        factoryBean.setResources(resource);

        return factoryBean.getObject();
    }

    private Map<String, Object> load(Resource resource) {
        return new Processor(resource).process();
    }

    private static class Processor extends YamlProcessor {

        Processor(Resource resource) {
            super.setResources(resource);
        }

        Map<String, Object> process() {
            final Map<String, Object> result = new LinkedHashMap<>();
            process(new MatchCallback() {
                @Override
                public void process(Properties properties, Map<String, Object> map) {
                    result.putAll(getFlattenedMap(map));
                }
            });
            return result;
        }
    }
}

